<?php

class poster{
	
var $db;
var $ctr;
function poster($database,$controller)
{
	$this->db = $database;
	$this->ctr = $controller;
}

function generate_post($thematic = 2)
{
	$name = $this->ctr->get_name();
	$email = $this->ctr->get_email();
	$phone = $this->ctr->get_phone();
	$title = $this->ctr->get_title($thematic);
	$description = $this->ctr->compile_full($thematic);
    $newpost = array(
	'name' => $name,
    'phone' => $phone,
    'email' => $email,
    'title' => $title,
    'description' => $description,    		
    		);
	/*$title = $this->ctr->get_title($thematic);
    		var_dump($title);*/
    return $newpost;
    
}



function post($post)
{
	if(empty($post))
	{
		return false;
	}
	$this->send_form($post);
	
	
}

function send_form($post)
{
	$image = $this->create_image_set();
	//var_dump($image);
	$filesdir = $_SERVER['DOCUMENT_ROOT'].'/images/'.'2';
	$path = $filesdir.'/'.$image[0];
	$parameters = array (
			'private' => '1',
			'seller_name' => $post['name'],
			'manager' => '',
			'email' => $post['email'],
			'phone' => (string)$post['phone'],
			//'region_id' => '637640',
			'location_id' => '637640',
			'metro_id' => (string)rand(37,147),
			'district_id' => '',
			'category_id' => '114',
			'params%5B716%5D' => '10208',
			'title' => $post['title'],
			'description' => $post['description'],
			'price' => '0',
		    'images[]' => '@'.$path,
			'service_code' =>'free',
			'main_form_submit' => '%D0%9F%D1%80%D0%BE%D0%B4%D0%BE%D0%BB%D0%B6%D0%B8%D1%82%D1%8C+%D1%81+%D0%BF%D0%B0%D0%BA%D0%B5%D1%82%D0%BE%D0%BC+%C2%AB%D0%9E%D0%B1%D1%8B%D1%87%D0%BD%D0%B0%D1%8F+%D0%BF%D1%80%D0%BE%D0%B4%D0%B0%D0%B6%D0%B0%C2%BB'
			);
	

	//var_dump($images);
	/*foreach ($images as $id => $image)
	{C:/xampp/htdocs/images/2/otoplenie_radiator.jpg
		$imagespost .= '&images[]='.$image->id;
	}*/
	$paramstr = '';
	//$imagespost = '&images[]='."@$path";
	//$parameters .= $imagespost;
	foreach ($parameters as $param => $value)
	{
		$paramstr .= $param.'='.$value.'&';
	}
	
	$paramstr = substr($paramstr, 0, strlen($paramstr)-1);
	//$parameters = $paramstr;
//var_dump($parameters);
	//var_dump($parameters);
	
	$ch = curl_init();
	$result = $this->curl_get($parameters, "http://m.avito.ru/add", "http://m.avito.ru/add");
	//$result = str_replace ('"Далее"', '"Далее" id="sbmtbtn"',$result);
	
	//$result = str_replace ('action="/add/confirm"', 'action="http://m.avito.ru/add/confirm"',$result);
	$result = str_replace ('action="/add/confirm"', 'action="http://m.avito.ru/add/confirm"',$result);
	$result = str_replace ("href='/add'", "href='http://m.avito.ru/add'",$result);
	//var_dump($_C);
	print $result;
	
	/*echo "<script>

	document.getElementById('phone').value = '";
	echo $post['phone'];
	echo "';	
	//document.getElementById('sbmtbtn').click();
	//document.myform.submit();
	</script>";
	//$this->add_image();*/
}

function confirm()
{
	
	print '9999999';
}

function download_captcha()
{
	$ch = curl_init('http://img.yandex.net/i/www/logo.png');
	$fp = fopen('./images/logo.png', 'wb');
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_exec($ch);
	curl_close($ch);
	fclose($fp);
	
}


function curl_get($parameters,$host, $referer = null){
	//$parameters='private=1&seller_name=&manager=&email=lkjlkjl%40jj.ww&phone=65456464656&location_id=637640&metro_id=2&district_id=&category_id=114&params%5B716%5D=10213&title=Kljlk&description=.knk.ml&price=0&image=&service_code=free';
	$ch = curl_init();
	
	//$cookie = str_replace('\\', '/', dirname(__FILE__)) . 'cookie.txt';
	$handle = fopen("cookie.txt", "w");
	//var_dump($parameters);die;
	//curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_REFERER, $referer);
	curl_setopt($ch, CURLOPT_URL, $host);
	curl_setopt($ch, CURLOPT_COOKIEJAR,$_SERVER['DOCUMENT_ROOT'].'/cookie.txt');
	curl_setopt($ch, CURLOPT_COOKIEFILE,$_SERVER['DOCUMENT_ROOT'].'/cookie.txt');
	curl_setopt($ch, CURLOPT_POST, 1);//var_dump($parameters);die;
	curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	curl_setopt ($ch, CURLOPT_VERBOSE, 2); // Отображать детальную информацию о соединении
	curl_setopt ($ch, CURLOPT_ENCODING, 0);
	//curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	
	$hdr=array(
			'User-Agent: BlackBerry9530/4.7 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/105',
			'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'Host	http://m.avito.ru',
			'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
			'Accept-Encoding: gzip, deflate',
			
			'Connection: keep-alive',
			'Content-Type: application/x-www-form-urlencoded',
			 
	);
	curl_setopt($ch, CURLOPT_HTTPHEADER,$hdr);
	$html = curl_exec($ch);
    //var_dump(curl_getinfo($ch));
    $html = str_replace('/captcha?','http://m.avito.ru/captcha?',$html);
    //$html = str_replace('form action="/add/confirm"','form action="http://m.avito.ru/add/confirm"',$html);
	echo curl_error($ch);
	curl_close($ch);

	return $html;
}



function load_image($file)
{
	$upload = $file;
	//var_dump($upload);
    $postdata = array( 
                   'image' => "@".$upload ); 

	$ch = curl_init(); 
	//curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_URL, 'http://m.avito.ru/add'); 
	curl_setopt($ch, CURLOPT_REFERER, 'http://m.avito.ru/add');
	curl_setopt ($ch, CURLOPT_VERBOSE, 2); // Отображать детальную информацию о соединении
	curl_setopt ($ch, CURLOPT_ENCODING, 0);
	curl_setopt($ch, CURLOPT_COOKIEJAR,$_SERVER['DOCUMENT_ROOT'].'/cookie.txt');
	curl_setopt($ch, CURLOPT_COOKIEFILE,$_SERVER['DOCUMENT_ROOT'].'/cookie.txt');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_POST, 1); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); 
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); 
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	$hdr=array(
			'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0',
			'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'Host	http://m.avito.ru',
			'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
			'Accept-Encoding: gzip, deflate',
			'Connection: keep-alive',
			'Content-Type: multipart/form-data',
	);
	
	$response = curl_exec($ch);  
	echo curl_error($ch);
	
	
	
	curl_close($ch);
	var_dump($response);die;
	$response = json_decode($response);
	
	return $response;
	
}


function load_image_set($typeid = 2, $count = 1)
{
	$set = $this->create_image_set($typeid ,$count);
	$filesdir = $_SERVER['DOCUMENT_ROOT'].'\\images\\'.$typeid;
	$uploadedarr = array();
	foreach($set as $id => $filename)
	{
		$path = $filesdir.'\\'.$filename;
		$uploadarr[] = $this->load_image($path);
	}
	
	return $uploadarr;
}




function create_image_set($typeid = 2,$countimages = 1)
{
	$filesdir = $_SERVER['DOCUMENT_ROOT'].'\\images\\'.$typeid;
	$files = scandir($filesdir);
	unset($files[0]);
	unset($files[1]);
	//var_dump($files);
	$count = count($files);
	$set = array();
	$i=1;
	while(!isset($set[$countimages]))
	{
		$num = rand(2,$count);
		if(!in_array($num,$set))
		{
			$set[$i] = $num;
			$i++;
		}
	}
	//var_dump($set);
	//var_dump($set);
	$filenamesarr = array();
	for($i=1;$i<=count($set);$i++)
	{
	    $filenamesarr[] = $files[$set[$i]];
	}
	
	
	return $filenamesarr;
    
}


/*
function comfirm_form()
{
	<p class="list_standard">Придумайте пароль для входа на сайт</p> <form action="/add/confirm" method="post" enctype="multipart/form-data"> <p> <label for="password">Пароль</label> <input type="password" name="password" id="password" class="short" value="" />
	</p> <p> <label for="confirm">Повторите пароль</label> <input type="password" name="confirm" id="confirm" class="short" value="" />
	</p>
	<p> <label for="captcha">Текст с картинки</label> <input type="text" id="captcha" name="captcha" class="shorter" /> <img src="/captcha?1382225995" id="captcha_img" alt="Картинка с кодом" width="90" height="20"/> <i class="icon-reload" id="captcha_refresh" title="обновить"></i>
	</p>
	
	<p class="b_top list_standard"> <input type="button" value="&larr; Назад" onclick="location.href='/add'"/>&#160;<input name="add" type="submit" value="Готово &rarr;" /> </p> </form>
}*/
	
}
?>